from  fastapi import  APIRouter,Depends, Query
from sqlalchemy.orm import  Session
from schemas.author.user import UserSchemas, login
from utils.get_db import get_db
from utils.logger import logger,TraceID
from models.author.user import User
from utils.security import create_access_token,check_access_token
from exception.excepts import  Failed
from utils.response import HttpResponse
import aioredis
from plugin.plugin_redis import get_redis_client


user = APIRouter()

@user.get("/user")
async def test(rolename:str = Query(None), payload:dict = Depends(check_access_token),redis:aioredis.Redis = Depends(get_redis_client)):
    user_id = await redis.get(payload.get("username"))
    # 自定义添加traceid
    # TraceID.set_trace(user_id, "user-api")
    logger.info(f"当前访问用户ID:{user_id}")
    return HttpResponse.success(data={"rolename":rolename})


@user.post("/add")
async def add(data:UserSchemas, db: Session = Depends(get_db)):
    try:
        logger.info("==========================>add user")
        db_user = User(username=data.username, password=data.password, nickname=data.nickname, email=data.email)
        db.add(db_user)
        db.commit()
        db.refresh(db_user)
        return {"username":db_user.username, "email":db_user.email }
    except Exception as e:
        db.rollback()
        logger.error(e)
        raise Failed(data=str(e))



@user.post("/login")
async def login(data:login, db: Session = Depends(get_db), redis:aioredis.Redis = Depends(get_redis_client)):
    logger.info("用户token获取")
    user_data = db.query(User).filter(User.username == data.username, User.password == data.password).first()
    if user_data:
        await redis.set(data.username, str(user_data.id))
        user_id = user_data.id
        token = create_access_token(str(user_id), data.username)
        return token
    else:
        return {"status": "error", "message": "用户名或密码错误"}